package com.chao.gateway.filter;

import cn.hutool.json.JSONUtil;
import com.chao.gateway.properties.IgnoreUrlsProperties;
import com.nimbusds.jose.JWSObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.text.ParseException;

/**
 * @author : Rookie
 * @description :
 * @date : 2022/1/25
 */
@Component
@Slf4j
@Order(0)
public class GlobalAuthFilter implements GlobalFilter {

    @Autowired
    private IgnoreUrlsProperties ignoreProperties;

    @Autowired
    private PathMatcher pathMatcher;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("鉴权过滤器被执行");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String requestUrl = request.getPath().value();
        log.info("当前请求地址：{}",requestUrl);

        //白名单url直接放行
        for (String whiteUrl : ignoreProperties.getWhiteUrls()) {
            if (pathMatcher.match(whiteUrl,requestUrl)){
                return chain.filter(exchange);
            }
        }

        String token = request.getHeaders().getFirst("Authorization");
        if (StringUtils.isBlank(token)){
            String body = JSONUtil.toJsonStr("token is null");
            DataBuffer dataBuffer = response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }
        String realToken = StringUtils.replace(token,"Bearer","");
        try{
            JWSObject jwsObject = JWSObject.parse(realToken);
            String userStr = jwsObject.getPayload().toString();
            log.info("user:{}",userStr);
            ServerHttpRequest httpRequest = request.mutate().header("userInfo", userStr).build();
            exchange = exchange.mutate().request(httpRequest).build();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return chain.filter(exchange);
    }
}
